# 态势相关
from typing import Any, Dict, List
import h3
from ..data_structures.base_structures import Map,HexCell

def _extract_coords(obj: Any) -> List[List[float]]:
    """
    从 feature 列表或单个 feature 中提取坐标列表，返回格式为 [[lon, lat], ...]
    支持 obj 为 list 或 dict，优先查找 region.coordinates，再查 geometry.coordinates。
    """
    if isinstance(obj, list) and len(obj) > 0:
        obj = obj[0]

    coords = None
    if isinstance(obj, dict):
        if 'region' in obj and isinstance(obj['region'], dict):
            region = obj['region']
            coords = region.get('coordinates', None)
        if coords is None and 'geometry' in obj and isinstance(obj['geometry'], dict):
            coords = obj['geometry'].get('coordinates', None)
        # 直接包含 coordinates 的情况
        if coords is None and 'coordinates' in obj:
            coords = obj.get('coordinates', None)

    if coords is None:
        raise ValueError("无法从输入中提取坐标，请检查输入结构。")

    # coordinates 可能是嵌套的 Polygon 结构：[[[lon, lat], ...]]
    if isinstance(coords, list) and len(coords) > 0 and isinstance(coords[0][0], (list, tuple)):
        ring = coords[0]
    else:
        ring = coords

    return [[float(pt[0]), float(pt[1])] for pt in ring]

def modify_status(map: Map, sample: Dict) -> Dict:
    # 提取点列表（[[lon, lat], ...]）
    coords = _extract_coords(sample)

    # 确保环是闭合的（首尾相同）
    ring = [ [float(lon), float(lat)] for lon, lat in coords ]
    if ring[0] != ring[-1]:
        ring.append(ring[0])

    # 构造 GeoJSON polygon（直接用提取的点序列）
    geojson = {
        "type": "Polygon",
        "coordinates": [ ring ]
    }

    # 生成 H3 索引
    resolution = 11
    h3_indexes = h3.polyfill_geojson(geojson, resolution)
    
    for cell in map.cells.values():
        cell:HexCell
        if cell.index in h3_indexes:
            cell.rejected = True

if __name__ == "__main__":
    sample = [{
        'region': {
            'type': 'Polygon',
            'coordinates': [[
                [119.0033621179218, 31.99185918926551],
                [119.00470226378457, 31.99185918926551],
                [119.00470226378457, 31.99290404875173],
                [119.0033621179218, 31.99290404875173],
                [119.0033621179218, 31.99185918926551]
            ]]
        },
        'properties': {'name': '1', 'category': '管制'},
        'source': 'qgis-plugin'
    }]

    map = Map()# 这里替换成将bin导入为map的代码

    modify_status(map,sample)